﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using UserManage;
using System.Data.SqlClient;
using Eb.MessageBox;
public partial class WebUserControl : System.Web.UI.UserControl
{
    UserManager _userManager = new UserManager();

    string _conString;
    public string ConString
    {
        get { return _conString; }
        set { _conString = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        btnBack.Attributes.Add("onmouseover", "this.style.backgroundColor='#00B5F0'");
        btnBack.Attributes.Add("onmouseout", "this.style.backgroundColor='#008FBF'");

        btnClear.Attributes.Add("onmouseover", "this.style.backgroundColor='#00B5F0'");
        btnClear.Attributes.Add("onmouseout", "this.style.backgroundColor='#008FBF'");
        btnSave.Attributes.Add("onmouseover", "this.style.backgroundColor='#00B5F0'");
        btnSave.Attributes.Add("onmouseout", "this.style.backgroundColor='#008FBF'");

        btnCreateLogin.Attributes.Add("onmouseover", "this.style.backgroundColor='#00B5F0'");
        btnCreateLogin.Attributes.Add("onmouseout", "this.style.backgroundColor='#008FBF'");

        btnChangePassword.Attributes.Add("onmouseover", "this.style.backgroundColor='#00B5F0'");
        btnChangePassword.Attributes.Add("onmouseout", "this.style.backgroundColor='#008FBF'");


        if (!IsPostBack)
        {
            btnSave.Enabled = true;
            btnClear.Enabled = true;
            if (Session["UserManager_Edit"] == "User Edit")
            {
                lblTitle.Text = "EDIT USER DETAILS";
                //InitializeDDL();
                LoadData();
                btnSave.Text = "Update";
            }
            else if (Session["UserManager_Edit"] == "User Add")
            {
                lblTitle.Text = "ADD NEW USER ";
                tblUser.Rows[2].Visible = false;
                btnSave.Text = "Save";
            }
            else if (Session["UserManager_Edit"] == "User Delete")
            {
                lblTitle.Text = "DELETE USER ";
                //InitializeDDL();
                //lnbDelete.Visible = true;
                btnSave.Enabled = false;
                btnClear.Enabled = false;
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string basePath = "~/Modules/";
        ViewState["LastLoaded"] = basePath + Session["UserManager_Control"];
        //if (Validate() == 1)
        //{
        //    return;
        //}
        if (Session["UserManager_Edit"] == "User Add")
        {
            Add();
        }
        else
        {
            Update();
        }
        Clear();      
    }
    protected void btnCreateLogin_Click(object sender, EventArgs e)
    {
        Session["UserManager_Control"] = "UserManager/ucUserRegister.ascx";
        Response.Redirect("BusinessProcessAutomation.aspx");
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        Clear();
    }
   
 
    
    //protected void ddlUserName_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    Clear();
    //    if (ddlUserName.SelectedIndex!=0)
    //        LoadData();
    //}
    //protected void CalDOB_SelectionChanged1(object sender, EventArgs e)
    //{
    //    txtDateofBirth.Text = CalDOB.SelectedDate.ToShortDateString(); 
    //    CalDOB.Visible = false;
    //}
    //protected void imbCalendar_Click(object sender, ImageClickEventArgs e)
    //{
    //   // CalDOB.Visible = true;
    //}

    //void InitializeDDL()
    //{
    //   // DataSet dsUser = user.GetData("UD_FirstName", "UD_UserPersonalID", "UserDetails");
    //    DataSet dsUser = _user.GetData("UserDetails", string.Empty);
           
    //    ddlUserName.DataSource = dsUser;
    //    ddlUserName.DataTextField = "UD_FirstName";
    //    ddlUserName.DataValueField = "UD_UserPersonalID";
    //    ddlUserName.DataBind();
    //    ddlUserName.Items.Insert(0, "Select");
    //}

    void LoadData()
    {
        try
        {
            //string condition = "UD_UserPersonalID = " + Session["UserManager_PersonalID"] + " ";

            string condition = "UD_UserPersonalID = " + ((string[])Session["UserManager_IDs"])[0] + " ";
            DataSet dsUser = _userManager.GetData("UserDetails", condition);

            //Session["UserManager_PersonalID"] = ddlUserName.SelectedValue;
            txtFirstName.Text = dsUser.Tables[0].Rows[0]["UD_FirstName"].ToString();
            txtMiddleName.Text = dsUser.Tables[0].Rows[0]["UD_MiddleName"].ToString();
            txtLastName.Text = dsUser.Tables[0].Rows[0]["UD_LastName"].ToString();
            txtNickName.Text = dsUser.Tables[0].Rows[0]["UD_NickName"].ToString();
            if (dsUser.Tables[0].Rows[0]["UD_Gender"].ToString().Trim() == "M")
                rblGender.SelectedIndex = 0;
            else //female
                rblGender.SelectedIndex = 1;
            string dateOfBirth = dsUser.Tables[0].Rows[0]["UD_DateOfBirth"].ToString();
            if (dateOfBirth != string.Empty)
                txtDateofBirth.Text = (dateOfBirth.Substring(0, dateOfBirth.IndexOf(" ")));

            txtAddress.Text = dsUser.Tables[0].Rows[0]["UD_Address"].ToString();
            txtPhone.Text = dsUser.Tables[0].Rows[0]["UD_Phone"].ToString();
            txtPersonalInformation.Text = dsUser.Tables[0].Rows[0]["UD_PersonalInformation"].ToString();
            txtSSN.Text = dsUser.Tables[0].Rows[0]["UD_SSN"].ToString();

            dsUser.Clear();
            //dsUser = _user.GetData("UserList", "UL_UserPersonalID='" + Session["UserManager_PersonalID"] + "'");
            dsUser = _userManager.GetData("UserList", "UL_UserPersonalID='" + ((string[])Session["UserManager_IDs"])[0] + "'");
            if (dsUser.Tables[0].Rows.Count == 0 && Session["UserManager_Edit"] == "User Edit")
            {
                btnCreateLogin.Enabled = true;
                btnChangePassword.Enabled = false;
            }
            else
            {
                btnCreateLogin.Enabled = false;
                btnChangePassword.Enabled = true;
            }
        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Load Data Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
    }

    int Validate()
    {
        //if ((Session["UserManager_Edit"] == "User Edit") && (ddlUserName.SelectedIndex == 0))
        //{

        //    Response.Write("<Script>alert('Select a User')</Script>");
        //    return 1;

        //}
        //if (txtFirstName.Text == string.Empty)
        //{
        //    Response.Write("<Script>alert('Enter First Name')</Script>");
        //    return 1;
        //}
        //else if (txtLastName.Text == string.Empty)
        //{
        //    Response.Write("<Script>alert('Enter Last Name')</Script>");
        //    return 1;
        //}
        
        //else if (rblGender.SelectedIndex == -1)
        //{
        //    Response.Write("<Script>alert('Select Gender')</Script>");
        //    return 1;
        //}
        //else if ((txtPhone.Text!=string.Empty ) && !(_user.CheckNumber(txtPhone.Text)))
        //{
        //    Response.Write("<Script>alert('Enter Valid Phone Number')</Script>");
        //    return 1;
        //}
       
        return 0;
    }


    void Add()
    {
        try
        {
            UserDetails userDetailsAdd = new UserDetails();
            userDetailsAdd.UserFirstName = txtFirstName.Text;
            userDetailsAdd.UserMiddleName = txtMiddleName.Text;
            userDetailsAdd.UserLastName = txtLastName.Text;
            userDetailsAdd.UserNickName = txtNickName.Text;
            userDetailsAdd.Gender = rblGender.SelectedValue;
            userDetailsAdd.Dob = txtDateofBirth.Text;
            userDetailsAdd.Address = txtAddress.Text;
            userDetailsAdd.Phone = txtPhone.Text;
            userDetailsAdd.PersonalInformation = txtPersonalInformation.Text;
            userDetailsAdd.SSN = txtSSN.Text;          

            if (_userManager.AddUser(userDetailsAdd))
            {
                Clear();
                btnCreateLogin.Enabled = true;
                btnChangePassword.Enabled = false;
                if (Session["UserManager_Picture"] != string.Empty )
                {
                     string condition = "UD_UserPersonalID IN (SELECT  MAX(UD_UserPersonalID) FROM UserDetails) ";
                     DataSet ds = _userManager.GetData("UserDetails", condition);
                     string userID = ds.Tables[0].Rows[0]["UD_UserPersonalID"].ToString();
                    _userManager.ImageUpload((byte[])Session["UserManager_Picture"],userID);
                }
                MessageBox.Show("Added Successfully");
               // Response.Write("<Script>alert('Added Successfully !')</Script>");// Message Box
            }
            else
            {
                MessageBox.Show("Username already exist!");

               // Response.Write("<Script>alert('User Already Exist !')</Script>"); //Message Box
            }
        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Add User Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
    }
    void Update()
    {
        try
        {
            UserDetails userDetailsEdit = new UserDetails();
            //userDetailsEdit.UserID = Session["UserManager_PersonalID"].ToString();
            userDetailsEdit.UserID = ((string[])Session["UserManager_IDs"])[0].ToString();
            userDetailsEdit.UserFirstName = txtFirstName.Text;
            userDetailsEdit.UserMiddleName = txtMiddleName.Text;
            userDetailsEdit.UserLastName = txtLastName.Text;
            userDetailsEdit.UserNickName = txtNickName.Text;
            userDetailsEdit.Gender = rblGender.SelectedValue;
            userDetailsEdit.Dob = txtDateofBirth.Text;
            userDetailsEdit.Address = txtAddress.Text;
            userDetailsEdit.Phone = txtPhone.Text;
            userDetailsEdit.PersonalInformation = txtPersonalInformation.Text;
            userDetailsEdit.SSN = txtSSN.Text;

            _userManager.EditUser(userDetailsEdit);
            MessageBox.Show("Updated Successfully");
            //Response.Write("<Script>alert('Updated Successfully !')</Script>");
        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Edit User Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
    }


    //void Delete()
    //{
    //    try
    //    {
    //        UserDetails userDetailsDelete = new UserDetails();
    //        userDetailsDelete.UserID = ddlUserName.SelectedValue.ToString();
    //        _user.DeleteUser(userDetailsDelete);
    //        Response.Write("<script>alert('Deleted Successfully !')</script>");
    //    }
    //    catch (Exception exp)
    //    {
    //        Session["ERRTITLE"] = "Delete User Failed";
    //        Session["ERRDET"] = exp.Message;
    //        Response.Redirect("ErrorPage.aspx");
    //    }
    //}

    void Clear()
    {
        try
        {
            txtFirstName.Text = string.Empty;
            txtMiddleName.Text = string.Empty;
            txtLastName.Text = string.Empty;
            txtNickName.Text = string.Empty;
            rblGender.SelectedIndex = -1;
            txtDateofBirth.Text = string.Empty;
            txtAddress.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtPersonalInformation.Text = string.Empty;
            txtSSN.Text = string.Empty;
        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Clear Controls Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
    }

    protected void lnbUsers_Click(object sender, EventArgs e)
    {
        Response.Redirect("UserSearch.aspx");
    }
    protected void lnbRoles_Click(object sender, EventArgs e)
    {
        Response.Redirect("UserRoleSearch.aspx");
    }

    protected void lnbUtilities_Click(object sender, EventArgs e)
    {
        Response.Redirect("Utility Search.aspx");
    }
    protected void lnbPermissions_Click(object sender, EventArgs e)
    {
        Response.Redirect("AddPermission.aspx");
    }
    protected void lnbHome_Click(object sender, EventArgs e)
    {
        Response.Redirect("UserHome.aspx");
    }
    protected void gvwUserDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {

    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Session["UserManager_Control"] = "UserManager/ucUserSearch.ascx";
        Response.Redirect("BusinessProcessAutomation.aspx");
    }
   

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        Upload();
        //  System.Threading.Thread.Sleep(3000);

    }

    void Upload()
    {
        //check whether an image is attached
        if (FileUploadImage.HasFile == false)
        {
            MessageBox.Show("Attach an Image");
           // Response.Write("<script>alert('Attach an Image')</script>");
            return;
        }

        //check the extention of the file
        string fileName = FileUploadImage.PostedFile.FileName;
        string extention = fileName.Substring(fileName.LastIndexOf("."));
        extention = extention.ToLower();
        if ((extention != ".jpg") && (extention != ".bmp") && (extention != ".gif"))
        {
            MessageBox.Show("Only files of type .jpg, .gif or .bmp are supported");
           // Response.Write("<script>alert('Only files of type .jpg, .gif or .bmp are supported')</script>");
            return;
        }

        //upload image

        int length = FileUploadImage.PostedFile.ContentLength;
        byte[] picture = new byte[length];
        FileUploadImage.PostedFile.InputStream.Read(picture, 0, length);
        Session["UserManager_Picture"] = picture;
        Session["UserManager_PictureLength"] = length;

        if (Session["UserManager_Edit"].ToString() == "User Edit")
        {
            string userID = ((string[])Session["UserManager_IDs"])[0].ToString();
            _userManager.ImageUpload(picture, userID);
        }
        // Response.Write("<script>alert('Uploaded Successfully !')</script>");
    }

    protected void btnChangePassword_Click(object sender, EventArgs e)
    {
        Session["UserManager_Control"] = "UserManager/ucChangePassword.ascx";
        Response.Redirect("BusinessProcessAutomation.aspx");
    }
}
